Skip to main content

Depth-First Search

Depth-First Search (DFS) is a fundamental graph traversal algorithm used to explore nodes and edges of a graph. Starting from a source node, DFS explores as far as possible along each branch before backtracking.

  1. Start at the root node (or any arbitrary node).
  2. Mark the starting node as visited and push it to a stack.
  3. While the stack is not empty:
    • Pop a node from the stack.
    • If the node has any unvisited adjacent nodes:
      • Mark the adjacent node as visited.
      • Push the adjacent node onto the stack.
  4. Repeat the process until the stack is empty.

3. How Does Depth-First Search Work?​

  • DFS explores nodes by going as deep as possible down each branch before backtracking to explore other branches.

4. Problem Description​

Given a graph, DFS aims to traverse the graph, visiting all the vertices and edges exactly once in a depthward motion.

5. Examples​

Example graph:

      0 - 1 - 2
| | |
3 - 4 - 5

6. Constraints​

  • The graph can be directed or undirected.
  • The graph may contain cycles.

7. Implementation​

Depth-First Search​

def dfs(graph, start):
visited = set()
stack = [start]

while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(set(graph[vertex]) - visited)

return visited

graph = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4],
4: [1, 3, 5],
5: [2, 4]
}

print(dfs(graph, 0))

8. Complexity Analysis​

  • Time Complexity: O(V+E)O(V + E) where VV is the number of vertices and EE is the number of edges.
  • Space Complexity: O(V)O(V) due to the stack and visited set.

9. Advantages and Disadvantages​

Advantages:​

  • Simple and easy to implement.
  • Can be used to detect cycles in a graph.
  • Useful for solving problems like topological sorting, pathfinding, and connectivity.

Disadvantages:​

  • May get stuck in an infinite loop if the graph contains cycles and the implementation does not account for visited nodes.
  • Not optimal for finding the shortest path in unweighted graphs.

10. References​